package com.chuangyang.fixboxmaster.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.chuangyang.fixboxlib.utils.StringUtils;
import com.chuangyang.fixboxlib.widgets.NoSwipeableViewPager;
import com.chuangyang.fixboxlib.widgets.tabView.IconPagerAdapter;
import com.chuangyang.fixboxlib.widgets.tabView.IconTabPageIndicator;
import com.chuangyang.fixboxmaster.BuildConfig;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.BaseInfo;
import com.chuangyang.fixboxmaster.bean.FirstNameEvent;
import com.chuangyang.fixboxmaster.bean.OrderOutTimeResult;
import com.chuangyang.fixboxmaster.service.FixBoxApi;
import com.chuangyang.fixboxmaster.service.GsonRequest;
import com.chuangyang.fixboxmaster.service.UploadLocationService;
import com.chuangyang.fixboxmaster.ui.fragment.BaseFragment;
import com.chuangyang.fixboxmaster.ui.fragment.home.BaseHomeFragment;
import com.chuangyang.fixboxmaster.ui.fragment.home.HomeFragment;
import com.chuangyang.fixboxmaster.ui.fragment.ProfileFragment;
import com.chuangyang.fixboxmaster.ui.fragment.repair.RepairListFragment;
import com.chuangyang.fixboxmaster.ui.widgets.BadgeView;
import com.chuangyang.fixboxmaster.utils.AlarmManagerUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;


public class MainActivity extends BaseActivity {
    private int mSelectPosition;
    public List<BaseFragment> fragments;
    Switch mSwitchOnOffline;
    TextView mAppName;
    NoSwipeableViewPager mViewPager;
    public static final String PUSH_MESSAGE_ENTER_MODE="PUSH_MESSAGE_ENTER_MODE";
    private int workState;
    private ImageView mMessageCenter;
    private BadgeView mBadgeView;
    int currentUnreadCount =-1;
    private LinearLayout mToolBarBg;
    private int currentPage;

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    mSelectPosition = position;
                    mSwitchOnOffline.setVisibility(View.VISIBLE);
                    mAppName.setVisibility(View.VISIBLE);
                    mAppName.setText("修一修");
                    mMessageCenter.setVisibility(View.VISIBLE);
                    if(currentUnreadCount>0){
                        mBadgeView.setVisibility(View.VISIBLE);
                        mBadgeView.setText(String.valueOf(currentUnreadCount));
                    }else {
                        mBadgeView.setVisibility(View.INVISIBLE);
                    }
                    mToolBarBg.setBackgroundColor(getResources().getColor(R.color.theme_primary));
                    mAppName.setTextColor(getResources().getColor(R.color.blue_background));
                    enableDisableSwipeRefresh(true);
                    currentPage=position;
                    break;
                case 1:
                    mSelectPosition = position;
                    mSwitchOnOffline.setVisibility(View.INVISIBLE);
                    mAppName.setVisibility(View.VISIBLE);
                    mAppName.setText("我的订单");
                    mMessageCenter.setVisibility(View.INVISIBLE);
                    mBadgeView.setVisibility(View.INVISIBLE);
                    mToolBarBg.setBackgroundColor(getResources().getColor(R.color.theme_primary));
                    mAppName.setTextColor(getResources().getColor(R.color.blue_background));
                    enableDisableSwipeRefresh(false);
                    currentPage=position;
                    break;
                case 2:
                    setTitle("个人中心");
                    mSelectPosition = position;
                    mSwitchOnOffline.setVisibility(View.INVISIBLE);
                    mAppName.setVisibility(View.VISIBLE);
                    mAppName.setText("个人中心");
                    mAppName.setTextColor(getResources().getColor(R.color.theme_primary));
                    mMessageCenter.setVisibility(View.INVISIBLE);
                    mBadgeView.setVisibility(View.INVISIBLE);
                    enableDisableSwipeRefresh(false);
                    mToolBarBg.setBackgroundColor(getResources().getColor(R.color.blue_background));
                    currentPage=position;
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        workState=getIntent().getIntExtra("workState",-1);
        setContentView(R.layout.activity_main);
        enableDisableSwipeRefresh(true);
        initViews();
        PushManager.startWork(getApplicationContext(),
                PushConstants.LOGIN_TYPE_API_KEY,
                StringUtils.getMetaValue(this, "api_key"));
        if(getIntent().getStringExtra(PUSH_MESSAGE_ENTER_MODE)!=null){
            switchPage(1);  //通过推送notification进来的自动跳转可接单页面
        }
        EventBus.getDefault().register(this);
        if(BuildConfig.DEBUG){
            AlarmManagerUtils.startPollingService(this, UploadLocationService.TEST_DELAY_TIME,
                    UploadLocationService.class, UploadLocationService.ACTION);
        }else {
            AlarmManagerUtils.startPollingService(this, UploadLocationService.DELAY_TIME,
                    UploadLocationService.class, UploadLocationService.ACTION);
        }
//        if(!BuildConfig.DEBUG){
//            checkOrderOutTime();
//        }
    }

    private void  checkOrderOutTime(){
        addRequest(new GsonRequest<>(FixBoxApi.GET_ORDER_TIME_OUT, OrderOutTimeResult.OrderOutTimeInfo.class, responseOrderTimeOut));
    }
    private Response.Listener<OrderOutTimeResult.OrderOutTimeInfo> responseOrderTimeOut=new Response.Listener<OrderOutTimeResult.OrderOutTimeInfo>() {
        @Override
        public void onResponse(OrderOutTimeResult.OrderOutTimeInfo response) {
            if(response.result.b2bOrderIds!=null&&response.result.b2bOrderIds.length>0){
                for(int i=0;i<response.result.b2bOrderIds.length;i++){
                    Intent intent = new Intent(MainActivity.this, ModuleActivity.class);
                    intent.putExtra(ModuleActivity.TYPE, ModuleActivity.B2B_ORDER_DETAL_ACTIVITY);
                    intent.putExtra(ModuleActivity.ORDER_ID, String.valueOf(response.result.b2bOrderIds[i]));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                    startActivity(intent); // Launch the LoginActivity
                }
            }
        }
    };


    public void onEvent(FirstNameEvent event) {
        if(event.workState==1){
            mSwitchOnOffline.setChecked(true);
        }else if(event.workState==0){
            mSwitchOnOffline.setChecked(false);
            Toast.makeText(MainActivity.this, "已切换到收工状态，你将无法收到订单通知", Toast.LENGTH_SHORT).show();
        }
        mSwitchOnOffline.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    HashMap<String,String> params=new HashMap<>();
                    params.put("workState","1");
                    addRequest(new GsonRequest<>(FixBoxApi.GET_ONLINE_OFFLINE, params, BaseInfo.class, responseOnlineListener));
                }else{
                    HashMap<String,String> params=new HashMap<>();
                    params.put("workState","0");
                    addRequest(new GsonRequest<>(FixBoxApi.GET_ONLINE_OFFLINE, params, BaseInfo.class, responseOfflineListener));
                }
            }
        });
        currentUnreadCount=event.notreadTotal;
        if(event.notreadTotal>0&&currentPage==0){
            mBadgeView.setVisibility(View.VISIBLE);
            mBadgeView.setText(String.valueOf(currentUnreadCount));
        }else {
            mBadgeView.setVisibility(View.INVISIBLE);
        }
    }



    private void initViews() {
        mSwitchOnOffline = (Switch) findViewById(R.id.btn_switch_online_offline);
         mToolBarBg=(LinearLayout)findViewById(R.id.toolbar_bg);
        if(workState==1){
            mSwitchOnOffline.setChecked(true);
        }else if(workState==0){
            mSwitchOnOffline.setChecked(false);
        }
        mAppName = (TextView) findViewById(R.id.app_name);
        mViewPager = (NoSwipeableViewPager) findViewById(R.id.view_pager);
        mMessageCenter = (ImageView) findViewById(R.id.iv_message_center);
        mMessageCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,MessageCenterActivity.class));
            }
        });
        mBadgeView= (BadgeView)findViewById(R.id.is_unread);

        IconTabPageIndicator mIndicator = (IconTabPageIndicator) findViewById(R.id.indicator);
        List<BaseFragment> fragments = initFragments();
        FragmentAdapter adapter = new FragmentAdapter(fragments, getSupportFragmentManager());
        mViewPager.setAdapter(adapter);
        mViewPager.setOffscreenPageLimit(3);
        mIndicator.setViewPager(mViewPager);
        mIndicator.setOnPageChangeListener(onPageChangeListener);


    }


    private void showDialog(String currentState) {
        AlertDialog.Builder cancelOrderDlg = new AlertDialog.Builder(MainActivity.this);
        cancelOrderDlg.setTitle("提示");
        cancelOrderDlg.setMessage(currentState);
        cancelOrderDlg.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        cancelOrderDlg.show();
    }



    private Response.Listener<BaseInfo> responseOfflineListener=new Response.Listener<BaseInfo>() {
        @Override
        public void onResponse(BaseInfo response) {
            if(!( MainActivity.this).isFinishing())
            {
                showDialog("已切换到收工状态，你将无法收到订单通知");
            }
        }
    };

    private Response.Listener<BaseInfo> responseOnlineListener=new Response.Listener<BaseInfo>() {
        @Override
        public void onResponse(BaseInfo response) {
            if(!( MainActivity.this).isFinishing())
            {
                showDialog("已切换到开工状态，你将收到所有订单通知");
            }
        }
    };


    private List<BaseFragment> initFragments() {
        fragments = new ArrayList<>();

        RepairListFragment repairListFragment = new RepairListFragment();
        repairListFragment.setTabTitle("接单");
        repairListFragment.setTabIconId(R.drawable.tab_my_order_selector);
        fragments.add(repairListFragment);

        BaseHomeFragment homeFragment = new BaseHomeFragment();
        homeFragment.setTabTitle("订单");
        homeFragment.setTabIconId(R.drawable.tab_index_selector);
        fragments.add(homeFragment);


        ProfileFragment profileFragment = new ProfileFragment();
        profileFragment.setTabTitle("我的");
        profileFragment.setTabIconId(R.drawable.tab_my_profile_selector);
        fragments.add(profileFragment);

        return fragments;
    }


    private class FragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
        private List<BaseFragment> mFragments;

        public FragmentAdapter(List<BaseFragment> fragments, FragmentManager fm) {
            super(fm);
            mFragments = fragments;
        }


        @Override
        public Fragment getItem(int i) {
            return mFragments.get(i);
        }

        @Override
        public int getIconResId(int index) {
            return mFragments.get(index).getTabIconId();
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragments.get(position).getTabTitle();
        }
    }

    protected void requestDataRefresh() {
        if (mSelectPosition == 0) {
            ((RepairListFragment) fragments.get(mSelectPosition)).updateListView();
        } else if (mSelectPosition == 1) {
            ((HomeFragment) fragments.get(mSelectPosition)).updateListView();
        }
        onRefreshingStateChanged(false, 1000);
    }




    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                String action = bundle.getString("action");
                if (action != null && action.equals("price_success")) {
                    String orderID = intent.getExtras().getString(ModuleActivity.ORDER_ID);
                    intent = new Intent(MainActivity.this, ModuleActivity.class);
                    bundle = new Bundle();
                    bundle.putString(ModuleActivity.ORDER_ID, orderID);
                    bundle.putInt(ModuleActivity.TYPE, ModuleActivity.ORDER_DETAL_ACTIVITY);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        }
    }



    @Override
    public boolean canSwipeRefreshChildScrollUp() {
        for (int i = 0; i < fragments.size(); i++) {
            if (!fragments.get(i).getUserVisibleHint()) {
                continue;
            }
            return ViewCompat.canScrollVertically(fragments.get(i).getListView(), -1);
        }
        return false;
    }


    public void switchPage(int position){
        mViewPager.setCurrentItem(position);
    }


}
